/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.example;

import com.alibaba.druid.pool.DruidDataSource;
import com.je.bpm.engine.impl.util.ReflectUtil;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.io.InputStream;

/**
 * 数据源配置
 */
@Configuration
@PropertySource("jdbc.properties")
public class DataSourceConfig implements EnvironmentAware {

    private Environment environment;

    @Bean(name = "dataSource")
    public DataSource dataSource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(environment.getProperty("jdbc.driverClassName"));
        //设置链接地址
        ds.setUrl(environment.getProperty("jdbc.url"));
        //设置用户名
        ds.setUsername(environment.getProperty("jdbc.username"));
        //设置密码
        ds.setPassword(environment.getProperty("jdbc.password"));
        //设置验证查询
        ds.setValidationQuery(environment.getProperty("jdbc.validationQuery"));
        //单位：秒，检测连接是否有效的超时时间。底层调用jdbc Statement对象的void setQueryTimeout
        ds.setValidationQueryTimeout(600);
        //初始化大小
        ds.setInitialSize(environment.getProperty("jdbc.initialSize",Integer.class));
        ds.setMinIdle(environment.getProperty("jdbc.minIdle",Integer.class));
        ds.setMaxActive(environment.getProperty("jdbc.maxActive",Integer.class));
        //配置获取连接等待超时的时间
        ds.setMaxWait(60000);
        //配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
        ds.setTimeBetweenEvictionRunsMillis(60000);
        //配置一个连接在池中最小生存的时间，单位是毫秒
        ds.setMinEvictableIdleTimeMillis(200000);
        ds.setTestWhileIdle(true);
        //这里建议配置为TRUE，防止取到的连接不可用
        ds.setTestOnBorrow(false);
        ds.setTestOnReturn(false);
        //打开PSCache，并且指定每个连接上PSCache的大小
        ds.setPoolPreparedStatements(true);
        //配置每个链接最大打开的Statement数量
        ds.setMaxPoolPreparedStatementPerConnectionSize(20);
        //这里配置提交方式，默认就是TRUE，可以不用配置
        ds.setDefaultAutoCommit(true);
        //超过时间限制是否回收
        ds.setRemoveAbandoned(false);
        //回收超时时间；单位为秒。180秒=3分钟
        ds.setRemoveAbandonedTimeout(60);
        //关闭abanded连接时输出错误日志
        ds.setLogAbandoned(true);
        return ds;
    }

//    @Bean(name = "sqlSessionFactory")
//    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws IOException {
//        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
//        sqlSessionFactoryBean.setDataSource(dataSource);
//        //设置扫描目录
//        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//        Resource[] resources = resolver.getResources("classpath*:mapping/*.xml");
//        System.out.println("----------------------------Mapper扫描-----------------------------------------");
//        for (Resource eachResource : resources) {
//            System.out.println("mybatis resolve mapper:" + eachResource.getURL());
//        }
//        System.out.println("----------------------------Mapper扫描-----------------------------------------");
//        sqlSessionFactoryBean.setMapperLocations(resources);
//
//        Properties properties = new Properties();
//        //set default properties
//        properties.put("limitBefore", "");
//        properties.put("limitAfter", "");
//        properties.put("limitBetween", "");
//        properties.put("limitOuterJoinBetween", "");
//        properties.put("limitBeforeNativeQuery", "");
//        properties.put("orderBy", "order by ${orderByColumns}");
//        properties.put("blobType", "BLOB");
//        properties.put("boolValue", "TRUE");
//        properties.load(getResourceAsStream("com/je/bpm/db/properties/mysql.properties"));
//        sqlSessionFactoryBean.setConfigurationProperties(properties);
//
//        TypeHandler[] typeHandlers = new TypeHandler[]{
//                new ByteArrayRefTypeHandler()
//        };
//        sqlSessionFactoryBean.setTypeHandlers(typeHandlers);
//
//        Class[] typeAlias = new Class[]{
//                ByteArrayRefTypeHandler.class
//        };
//        sqlSessionFactoryBean.setTypeAliases(typeAlias);
//        return sqlSessionFactoryBean;
//    }

    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    protected InputStream getResourceAsStream(String resource) {
        return ReflectUtil.getResourceAsStream(resource);
    }

}

